package org.vuzya.motivateme.activities;

import static org.vuzya.motivateme.helpers.ConstantHelper.dateFormater;
import static org.vuzya.motivateme.helpers.ConstantHelper.EXTRA_BUSINESS_ID;

import java.text.ParseException;
import java.util.Date;

import org.vuzya.motivateme.R;
import org.vuzya.motivateme.db.DBHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

public class NewBusinessActivity extends Activity {
	private static final String TAG = "NEW_BUSINESS_ACTIVITY";
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_business);
    }
	
	public void createBusiness(View v){
		final EditText ETtitle = (EditText)findViewById(R.id.create_business_title_edittext);
		final EditText ETdescription = (EditText)findViewById(R.id.create_business_description_edittext);
		final DatePicker dp = (DatePicker)findViewById(R.id.create_business_start_date_datepicker);
		final String title = ETtitle.getText().toString();
		if(title==null||title==""||title.length()==0){
			Toast.makeText(this, R.string.business_enter_title, Toast.LENGTH_LONG).show();
			return;
		}
		final String description = ETdescription.getText().toString();
		final String date = String.format("%04d-%02d-%02d", dp.getYear(), dp.getMonth()+1, dp.getDayOfMonth());
		Date d;
		try {
			d = dateFormater.parse(date);
		} catch (ParseException e) {
			Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show(); // It not gonna happen.
			Log.e(TAG, "Something impossible happens... It's at the 'it not gonna happen' comment.");
			return;
		}
		Date dd = new Date();
		dd.setHours(0);
		dd.setMinutes(0);
		dd.setSeconds(0);
		dd.setTime((dd.getTime()/1000)*1000);
		if(d.compareTo(dd)>0){
			Toast.makeText(this, R.string.business_enter_correct_startdate, Toast.LENGTH_LONG).show();
			return;
		}
		
		DBHelper dbh = new DBHelper(this);
		try{
			long id = dbh.addBusiness(title, description, date);
			Intent i = new Intent(this, TestActivity.class);
			i.putExtra(EXTRA_BUSINESS_ID, id);
			startActivity(i);
		} catch (Exception e) {
			Log.e(TAG, "Something goes wrong during 'business' inserting...");
		} finally {
			dbh.close();
		}
		// TODO: uncomment next line =)
		finish();
	}
}